package chat

import (
	"bytes"
	"encoding/json"
	"fmt"
	"regexp"
	"strings"
)

const (
	msgTypeSendText  = 0
	msgTypeSendFace  = 1
	msgTypeSendImage = 2
	msgTypeSendAudio = 3
	msgTypeSendVideo = 4
)

type ReplyMsg struct {
	Content string `json:"content"` // 消息内容
}

const (
	CMD_HEART = 1 // 心跳消息，不处理
	CMD_MSG   = 2 // 普通消息
)

const (
	TYPE_TEXT                   = 1  // 文字
	TYPE_IMG                    = 2  // 图片
	TYPE_FILE                   = 3  // 文件
	TYPE_WELCOME                = 4  // 欢迎用户
	TYPE_COMMON_QUESTIONS       = 5  // 常见问题
	TYPE_ASK_QUESTION           = 6  // 访客问问题
	TYPE_AUTO_REPLY_QUESTION    = 7  // 自动回复访客问题
	TYPE_NOTIFY_ONLINE          = 8  // 通知上线
	TYPE_NOTIFY_OFFLINE         = 9  // 通知下线
	TYPE_NOTIFY_REPLACE_SERVICE = 10 // 通知更换客服
)

type Message struct {
	Cmd        uint8      `json:"cmd" validate:"required" label:"管道类型"`
	ChannelId  string     `json:"channel_id"` // 管道ID
	UserUuid   string     `json:"user_uuid"`
	ToUserUuid string     `json:"to_user_uuid" validate:"required" label:"对方id"`
	Type       uint8      `json:"type" validate:"required" label:"消息类型"`    // 消息类型
	Content    string     `json:"content" validate:"required" label:"消息内容"` // 消息内容
	SendTime   string     `json:"send_time"`
	Children   []ReplyMsg `json:"children"`
}

func TrimHtml(src string) string {
	//将HTML标签全转换成小写
	re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
	src = re.ReplaceAllStringFunc(src, strings.ToLower)
	//去除STYLE
	re, _ = regexp.Compile("\\<style[\\S\\s]+?\\</style\\>")
	src = re.ReplaceAllString(src, "")
	//去除SCRIPT
	re, _ = regexp.Compile("\\<script[\\S\\s]+?\\</script\\>")
	src = re.ReplaceAllString(src, "")
	//去除所有尖括号内的HTML代码，并换成换行符
	re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
	src = re.ReplaceAllString(src, "\n")
	//去除连续的换行符
	re, _ = regexp.Compile("\\s{2,}")
	src = re.ReplaceAllString(src, "\n")

	return src
}

func (msg *Message) String() string {
	b, err := json.Marshal(*msg)
	if err != nil {
		return fmt.Sprintf("%+v", *msg)
	}
	var out bytes.Buffer
	err = json.Indent(&out, b, "", "    ")
	if err != nil {
		return fmt.Sprintf("%+v", *msg)
	}
	return out.String()
}

type messageInterface interface {
	SendMessage(msg Message)
	DelaySendMessage(msg Message)
	LoginServer(uuid string)
	LogoutServer(uuid string)
	ErrorLogServer(err error)
}

var msgStore messageInterface
